﻿using Microsoft.Owin.Cors;
using Owin;
using System.Collections.Generic;
using System.Net;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.Cors;
using WebApiThrottle;

namespace ldhWebApiWF
{
    public class WebApi
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            // Add a reference here to the new MediaTypeFormatter that adds text/plain support
            config.Formatters.Insert(0, new TextMediaTypeFormatter());
            var jsonFormatter = new JsonMediaTypeFormatter();
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

            //访问时间限制 限制生效后返回429
            config.MessageHandlers.Add(new ThrottlingHandler()
            {
                Policy = new ThrottlePolicy(perSecond: 6700)
                {
                    IpThrottling = true
                },
                Repository = new ConcurrentDictionaryRepository()
            });
            ////验证身份
            //appBuilder.Use(typeof(CheckIPMiddleware));

            //日志
            //appBuilder.Use(typeof(LoggingMiddleware));
            appBuilder.UseWebApi(config);

            //初始化rsa组件以防止实例化慢引至的系统错误
            RsaComputer.GetComputer();
        }
    }
}
